package com.itheima.service.impl;

import com.itheima.mapper.MemberMapper;
import com.itheima.service.MemberService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;


@Slf4j
@Service
public class MemberServiceImpl implements MemberService {
    @Autowired
    private MemberMapper memberMapper;

    @Override
    public List<Integer> findMemberCountByMonth(List<String> months) {
        List<Integer> memberCounts = new ArrayList<>();

        for (String month : months) {
            try {
                // 解析年月（格式：yyyy.MM）
                String[] parts = month.split("\\.");
                int year = Integer.parseInt(parts[0]);
                int monthNum = Integer.parseInt(parts[1]);

                // 获取当月最后一天
                YearMonth yearMonth = YearMonth.of(year, monthNum);
                LocalDate lastDayOfMonth = yearMonth.atEndOfMonth();

                // 格式化为YYYY-MM-DD
                String formattedDate = lastDayOfMonth.format(DateTimeFormatter.ISO_LOCAL_DATE);

                // 查询当月会员数
                Integer count = memberMapper.findMemberCountBeforeDate(formattedDate);
                memberCounts.add(count);
            } catch (Exception e) {
                // 处理异常，避免单个月份错误导致整个统计失败
                log.error("计算会员数量时出错，月份: {}", month, e);
                memberCounts.add(0); // 添加默认值或抛出更具体的异常
            }
        }

        return memberCounts;
    }
}
